package com.indexingsystem.boss.utils;


import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;


/**
 * 视频文件复制文件.
 * @author Administrator
 *
 */
public class StoreCopyFileThread extends Thread
{
    private String sourcePath;

    private String targerPath;

    private long start, end;

    public StoreCopyFileThread(String sourcePath, String targerPath, long start, long end)
    {
        super();
        this.sourcePath = sourcePath;
        this.targerPath = targerPath;
        this.start = start;
        this.end = end;
    }

    public void run()
    {
        try
        {
            long beginTime = System.currentTimeMillis();
            System.out.println("开始时间:" + beginTime);
            // 创建只读的随机访问文件
            RandomAccessFile in = new RandomAccessFile(sourcePath, "r");

            // 创建可读写的随机访问文件
            RandomAccessFile out = new RandomAccessFile(targerPath, "rw");

            // 将输入跳转到指定位置

            in.seek(start);

            // 从指定位置开始写
            out.seek(start);

            // 文件输入通道
            FileChannel inChannel = in.getChannel();

            // 文件输出通道
            FileChannel outChannel = out.getChannel();

            // 锁住需要操作的区域false代表锁住
            FileLock lock = outChannel.lock(start, (end - start), false);

            // 将字节从此通道的文件输到指定的可写入字节的输出通道
            inChannel.transferTo(start, (end - start), outChannel);

            // 释放锁
            lock.release();

            // 从里到外关闭文件
            out.close();
            in.close();
            long endTime = System.currentTimeMillis();

            System.out.println(Thread.currentThread().getName() + "-结束时间：" + endTime + "-共用时:"
                               + (endTime - beginTime));
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}